// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

export default class extends Base {
  /**
   * index action
   * @return {Promise} []
   */
	// 店家卡列表
	async cardlistAction(){
		let page = this.post();
		let pages = page.pages;
		let limits = page.limits;
		let search = page.search;
		let zt = page.zt;
		
		let shopid = this.shop_userinfo.departmentid;

		let list = await this.model('or_shop_card').where({shopid: shopid, isdisabled:zt, 'name|number':['like', '%'+search+'%']})
				.page(pages, limits)
				.order('no')
				.countSelect();

		return this.json(list);
	}

	// 开卡订单列表
	async opencardlistAction(){
		let page = JSON.parse(this.post('page'))
		let where = {
			's.departmentid':this.shop_userinfo.departmentid,
			's.ordertype':1,
			'g.name|g.phone|g.vipcard|a.name|s.order_sn':['like','%'+page.search+'%']
		}
		if (page.zt != 0) {
			where['s.status'] = page.zt - 1
		}
		//设置时间
		if (page.times && (page.times[0] != null && page.times[1] != null)) {
			let begintime = Math.floor(new Date(page.times[0]).setHours(0,0,0,0)/1000)
			let endtime = Math.floor(new Date(page.times[1]).setHours(0,0,0,0)/1000) + 86400
			where['s.addtime'] = {'>=': begintime, '<': endtime}
 		}

		let data = await this.model('or_shop_order')
								.alias('s')
								.field('s.id, s.order_sn, s.recemoney, s.usebalance, s.usegiftbalance, s.status, s.addtime, IF(s.remarks!="",s.remarks,"无") as remarks, g.id as gid, g.name as gname,g.phone as gphone,g.vipcard,a.name as aname,z.name as zname')
								.join('think_or_guest g on s.guestid = g.id')
								.join('think_or_admin a on s.operatorid = a.id')
								.join('think_or_admin z on s.auditorid = z.id')
								.page(page.pages, page.limits)
								.order('id DESC')
								.where(where)
								.countSelect();
		return this.json(data);
	}

	// 开卡操作
	async opencardAction(){
		/*
		* 只开卡，不结账
		* 如果可以开多张卡，则把赠送的品项绑定到当前订单ID上（如果退卡则通过当前订单ID调出赠送的品项）
		* 写入表[or_shop_order、or_shop_orderinfo]两张表
		* 不结账可以直接删除当前订单，也可以编辑当前订单。
		*/
		let data = JSON.parse(this.post('data'));

		// 判断客户期初是否审核未审核不能开卡
		let isinitial = await this.model('or_guest').where({id: data.ginfo.id}).getField('initial_info', true)
		if (isinitial == 0) {
			return this.fail('该客户期初未审核不能开单！');
		} 
		let ginfo = data.ginfo, cards = data.cards
		let shopid = this.shop_userinfo.departmentid;
		let addtime = Math.round(new Date().valueOf()/1000);
		let ordersn = await this.getordersn('KKD',1)
		let model = this.model('or_shop_order');
		await model.transaction(async()=> {
			try{
				let addorder = {
					order_sn: ordersn,
					guestid: ginfo.id,
					departmentid: shopid,
					recemoney: data.order.usemoney,
					cardreduce: 0,
					usebalance: data.order.usebalance,
					usegiftbalance: data.order.usegiftbalance,
					operatorid: this.shop_userinfo.id,
					status: 0,
					addtime: addtime,
					ordertype: 1,
					remarks: data.order.remarks
				}
				let orderid = await model.add(addorder);
				if (!orderid) {
					await model.rollback();
					return this.fail('开卡失败');
				}
				// 更新客户备注（这个暂时不放在回滚里面删除订单时无法退回）
				let resguest = await this.model('or_guest').db(model.db()).where({id: ginfo.id}).update({remarks: ginfo.remarks})

				let addorderinfo = []
				for(var i = 0, cardlen = cards.length; i < cardlen; i++){
					addorderinfo.push({
						departmentid: shopid,
						orderid: orderid,
						consumetype: 1,
						type: cards[i].rowtype,
						typeid: cards[i].id,
						typename: cards[i].name,
						num: cards[i].num,
						price: cards[i].price,
						totalprice: cards[i].num * cards[i].price,
						discount: cards[i].discount,
						amount: cards[i].amount,
						usemoney: cards[i].usemoney,
						usebalance: cards[i].usebalance,
						usegiftbalance: cards[i].usegiftbalance,
						usecard: 0,
						isgift: cards[i].isgift ? 1 : 0,
						istemp: cards[i].rowtype == 1 ? 1 : 0,
						brandid: cards[i].brandid ? cards[i].brandid : 0,
						cost: cards[i].cost
					})
				}

				let addoinfo = await this.model('or_shop_orderinfo').db(model.db()).addMany(addorderinfo)

				if (addoinfo) {
					await model.commit();
					return this.success({info: '开卡成功', id: orderid});
				} else {
					await model.rollback();
					return this.fail('开卡失败');
				}
			}catch(e){
				console.log(e);
				await model.rollback();
				return this.fail('操作失败！');
			}
		})
	}

	async getkaikadaninfoAction () {
		let id = this.get('id')
		let order = await this.model('or_shop_order').where({id: id}).find();
		let ginfo = await this.model('or_guest')
		.alias('g')
		.field('g.*, v.vipname, v.goodsdiscount, v.subjectdiscount')
		.join('left join `think_or_guest_vipgrade` v on g.level = v.id')
		.where({'g.id': order.guestid})
		.find()	
		let orderlist = await this.model('or_shop_orderinfo')
		.alias('o')
		.field('o.*, c.category as cardtype, c.validity')
		.join('left join `think_or_shop_card` c on o.typeid = c.id and o.type = 3')
		.where({'o.orderid': id})
		.select()

		// 结账信息
		let accountlist = await this.model('or_shop_accountlog')
		.alias('l')
		.field('a.*, l.money as paymoney, l.accountid')
		.join('left join `think_or_shop_account` a on l.accountid = a.id')
		.where({'l.orderid': id, 'l.ordertype': 'KKD'})
		.select()

		let yejilist = await this.model('or_shop_yejiticheng')
		.alias('y')
		.field('y.*,u.name')
		.join('left join `think_or_app_user` u on y.userid = u.id')
		.where({'y.ordertype': 'KKD', 'y.orderid': id, 'addtype': 0})
		.select()

		let data = {
			order: order,
			orderlist: orderlist,
			ginfo: ginfo,
			accountlist: accountlist,
			yejilist: yejilist
		}
		return this.json(data)
	}

	// 开卡结账功能
	async opencardjiezhangAction(){
		// 开卡结账操作开始
		let data = JSON.parse(this.post('data'))

		// 取出订单信息和list
		let order = await this.model('or_shop_order').where({id: data.order.id}).find()
		if (order.status > 0) {
			return this.fail('当前订单已结账！')
		}

		let orderlist = await this.model('or_shop_orderinfo').where({orderid: data.order.id}).select()

		let orderid = data.order.id
		let shopid = this.shop_userinfo.departmentid, addtime = order.addtime;
		// 结账事务开始
		let model = this.model('or_shop_order');
		await model.transaction(async () => {
			try {
				/*
				* 1、首先取出order订单信息
				* 2、获取orderinfo信息（开的哪些卡和赠送的哪些品项）
				* 3、根据cardid把机构的卡项添加到客户的卡项表里（注：机构卡拉取次数要自增）
				* 4、根据cardid把机构的品项取出并添加到客户的卡项表里
				* 5、把赠送的品项添加到客户的暂存仓库里
				* 6、店家账户收款金额更新，并记录收款日志表
				* 7、如果有消耗业绩或现金业绩，则把对应的业绩分配写到对应的表里
				* 8、更新客户表信息
				* 	-> 根据客户余额消费减去相应的余额，
				*		-> 把消费信息记录到客户消费金额流量表里，
				*		-> 并且更新顾客最后到店时间
				* 9、订单信息处理后重新更新当前订单信息（主要是订单的现金消费和余额消费等）
				*/
				
				// 先做订单审核操作	
				let resorder = await model.where({id: orderid}).update({
					status: 1,
					auditorid: this.shop_userinfo.id
				})

				let cardsubjectdata = [], goodsdata = [], goodsdatalog = [], zancundata = []
				let rescardsubject = 1, resgoods = 1, resgoodslog = 1, reszancun = 1
				// 接着循环订单详细表进行操作
				for (var i = orderlist.length - 1; i >= 0; i--) {
					
					// 如果是卡，取出卡信息写入客户卡表和卡项表
					if (orderlist[i].type == 3) {
						// 取出原生卡项
						let card = await this.model('or_shop_card')
						.alias('c')
						.db(model.db())
						.join('left join `think_or_shop_cardsubject` s on c.id = s.cardid')
						.where({'c.id': orderlist[i].typeid})
						.select()
						// 推送项目
						for (var k = card.length - 1; k >= 0; k--) {
							// 期卡暂时卡耗业绩社为零
							// 判断是否有成本扣除
							let cost = orderlist[i].cost > 0 ? orderlist[i].cost : 0
							let amount = card[k].category == 1 ? 0 : card[k].disprice * orderlist[i].discount * card[k].num * (1 - cost / 100)
							let discount = card[k].category == 1 ? 0 : amount / (card[k].price * card[k].num)
							cardsubjectdata.push({
								guestid: order.guestid,
								subjectid: card[k].subjectid,
								num: card[k].num,
								nownum: card[k].num,
								price: card[k].price,
								discount: discount,
								disprice: card[k].price * discount,
								amount: amount,
								cardtype: card[k].category,
								orderid: orderid,
								addtime: addtime,
								endtime: card[k].category == 1 ? addtime + card[k].validity * 86400 : 0,
								shopid: this.shop_userinfo.departmentid,
								cardid: orderlist[i].typeid,
								isdisabled: 0
							}) 
						}
					}
					// 如果是项目，同样写入卡项表
					if (orderlist[i].type == 2) {
						let cost = orderlist[i].cost > 0 ? orderlist[i].cost : 0
						let amount = orderlist[i].amount * (1 - cost / 100)
						let disprice = amount / orderlist[i].num
						cardsubjectdata.push({
							guestid: order.guestid,
							subjectid: orderlist[i].typeid,
							num: orderlist[i].num,
							nownum: orderlist[i].num,
							price: orderlist[i].price,
							discount: disprice / orderlist[i].price,
							disprice: disprice,
							amount: amount,
							cardtype: 2,
							orderid: orderid,
							addtime: addtime,
							endtime: 0,
							shopid: this.shop_userinfo.departmentid,
							cardid: 0,
							isdisabled: 0
						}) 
					}
					// 如果是产品减库存，写库存日志，如果有暂存写暂存
					if (orderlist[i].type == 1) {
						let goods = await this.model('or_shop_goods').db(model.db()).where({goodsid: orderlist[i].typeid, shopid: shopid}).find()
						goods.nums -= Number(orderlist[i].num)
						goodsdata.push(goods)
						goodsdatalog.push({
							departmentid: shopid,
							goodsid: orderlist[i].typeid,
							ordertype: 'KKD',
							orderid: orderid,
							nums: -1 * orderlist[i].num,
							addtime: order.addtime,
							posttime: addtime
						})
						if (orderlist[i].istemp == 1) {
							zancundata.push({
								guestid: order.guestid,
								goodsid: orderlist[i].typeid,
								price: orderlist[i].price,
								num: orderlist[i].num,
								nownum: orderlist[i].num,
								disprice: orderlist[i].price * orderlist[i].discount,
								amount: orderlist[i].amount,
								orderid: orderid,
								shopid: this.shop_userinfo.departmentid,
								addtime: addtime,
								isgift: orderlist[i].isgift,
								isdisabled: 0,
								brandid: orderlist[i].brandid
							})
						}
					}
				}

				if (cardsubjectdata.length > 0) {
					rescardsubject = await this.model('or_shop_guestcardsubject').db(model.db()).addMany(cardsubjectdata)
				}

				if (goodsdata.length > 0) {
					resgoods = await this.model('or_shop_goods').db(model.db()).updateMany(goodsdata)
					resgoodslog = await this.model('or_shop_goodslog').db(model.db()).addMany(goodsdatalog)
				}

				if (zancundata.length > 0) {
					reszancun = await this.model('or_shop_guest_temp_reserve').db(model.db()).addMany(zancundata)
				}

				// 开始处理银行信息
				// 查看是否有余额和赠送余额消费
				let guestaccount = {arrivetime: addtime}
				let resguestaccountlog = 1
				if (data.order.usebalance > 0 || data.order.usegiftbalance > 0) {
					let guest = await this.model('or_guest').db(model.db()).where({id: order.guestid}).find()
					if (guest.giftbalance - data.order.usegiftbalance < 0) {
						await model.rollback()
						return this.fail('该客户赠送余额不足以支付当前订单！')
					}

					guestaccount.balance = guest.balance - data.order.usebalance
					guestaccount.giftbalance = guest.giftbalance - data.order.usegiftbalance

					resguestaccountlog = await this.model('or_shop_guest_accountlog').db(model.db()).add({
						guestid: order.guestid,
						shopid: shopid,
						ordertype: 'KKD',
						orderid: orderid,
						balance: -1 * data.order.usebalance,
						giftbalance: -1 * data.order.usegiftbalance,
						addtime: addtime,
						type: 3
					})
				}

				let resguestaccount = await this.model('or_guest').db(model.db()).where({id: order.guestid}).update(guestaccount)

				// 处理账户余额
				let resaccount = 1, resaccountlog = 1
				if (data.paylist.length > 0) {
					let accountdata = [], accountdatalog = []
					for (var i = data.paylist.length - 1; i >= 0; i--) {
						let account = await this.model('or_shop_account').db(model.db()).where({id: data.paylist[i].accountid}).find()
						account.balance += Number(data.paylist[i].paymoney)
						accountdata.push(account)
						accountdatalog.push({
							departmentid: shopid,
							accountid: data.paylist[i].accountid,
							ordertype: 'KKD',
							type: 1,
							orderid: orderid,
							money: data.paylist[i].paymoney,
							addtime: addtime
						})
					}
					resaccount = await this.model('or_shop_account').db(model.db()).updateMany(accountdata)
					resaccountlog = await this.model('or_shop_accountlog').db(model.db()).addMany(accountdatalog)
				}

				let resxianjin = 1, resreduce = 1, resyeji = 1;
				// 现金业绩表
				// 重新规划业绩分配，暂时用两种方式
				if (data.yejilist.length > 0) {
					let yejidata = [], selluserList = [], reduceuserList = []
					data.yejilist.forEach((row) => {
						yejidata.push({
							shopid: shopid,
							orderid: data.order.id,
							ordertype: 'KKD',
							xianjinyeji: row.xianjinyeji,
							kahaoyeji: row.kahaoyeji,
							userid: row.userid,
							bumenid: row.bumenid,
							xiaozuid: row.xiaozuid,
							guestid: data.order.guestid,
							fuwutype: row.fuwutype,
							addtime: addtime
						})
						if (row.xianjinyeji > 0) {
							selluserList.push({
								orderid 	: data.order.id,
								feattype	: 'KKD',
								shopid 		: shopid,
								feat 		: row.xianjinyeji,
								userid 		: row.userid,
								bumenid 	: row.bumenid,
								xiaozuid 	: row.xiaozuid,
								guestid     : data.order.guestid,
								addtime 	: addtime
							})
						}
						if (row.kahaoyeji > 0) {
							reduceuserList.push({
								orderid 	: data.order.id,
								feattype	: 'KKD',
								shopid 		: shopid,
								feat 		: row.kahaoyeji,
								userid 		: row.userid,
								bumenid 	: row.bumenid,
								xiaozuid 	: row.xiaozuid,
								guestid     : data.order.guestid,
								addtime 	: addtime
							})
						}
					})

					if (selluserList.length > 0) {
						resxianjin = await this.model('or_shop_yejixianjin').db(model.db()).addMany(selluserList);
					}
					if (reduceuserList.length > 0) {
						resreduce = await this.model('or_shop_yejicardreduce').db(model.db()).addMany(reduceuserList);
					}
					resyeji = await this.model('or_shop_yejiticheng').db(model.db()).addMany(yejidata)
				}
		
				if (resreduce && resyeji && resxianjin && resorder && resguestaccount && resguestaccountlog && resaccount && resaccountlog && resgoods && resgoodslog && reszancun && rescardsubject) {
					await model.commit();
					return this.success('结账成功');
				} else {
					await model.rollback();
					return this.fail('结账失败');
				}
			} catch(e) {
				console.log(e);
				await model.rollback();
				return this.fail('结账失败');
			}
		});
	}

	// 编辑开卡订单操作
	async editopencardAction () {
		let data = JSON.parse(this.post('data'));
		let addtime = Math.round(new Date().valueOf()/1000);
		let shopid = this.shop_userinfo.departmentid;
		let order = data.order, cards = data.cards

		let isstatus = await this.model('or_shop_order').where({id: order.id, status:0}).find();
		if (think.isEmpty(isstatus)) {
			return this.fail('当前订单已结账！');
		}

		let model = this.model('or_shop_order');
		await model.transaction(async () => {
			try {
				
				let datas = {
					guestid: data.ginfo.id,
					recemoney: data.order.usemoney,
					cardreduce: 0,
					usebalance: data.order.usebalance,
					usegiftbalance: data.order.usegiftbalance,
					operatorid: this.shop_userinfo.id,
					remarks: order.remarks,
				}
				let resorder = await model.where({id: order.id}).update(datas)
				if (!resorder) {
					await model.rollback();
					return this.fail('更新订单失败');
				}
				// 刪除以前的
				let resdel = await this.model('or_shop_orderinfo').db(model.db()).where({orderid: order.id}).delete()

				let addorderinfo = []
				for(var i = 0, cardlen = cards.length; i < cardlen; i++){
					addorderinfo.push({
						departmentid: shopid,
						orderid: order.id,
						consumetype: 1,
						type: cards[i].rowtype,
						typeid: cards[i].id,
						typename: cards[i].name,
						num: cards[i].num,
						price: cards[i].price,
						totalprice: cards[i].num * cards[i].price,
						discount: cards[i].discount,
						amount: cards[i].amount,
						usemoney: cards[i].usemoney,
						usebalance: cards[i].usebalance,
						usegiftbalance: cards[i].usegiftbalance,
						usecard: 0,
						isgift: cards[i].isgift ? 1 : 0,
						istemp: cards[i].rowtype == 1 ? 1 : 0,
						brandid: cards[i].brandid ? cards[i].brandid : 0,
						cost: cards[i].cost
					})
				}
				// 更新客户备注（这个暂时不放在回滚里面删除订单时无法退回）
				let resguest = await this.model('or_guest').db(model.db()).where({id: data.ginfo.id}).update({remarks: data.ginfo.remarks})

				let resadd = await this.model('or_shop_orderinfo').db(model.db()).addMany(addorderinfo)

				if (resdel && resadd) {
					await model.commit();
					return this.success({info: '更改成功', id: order.id});
				} else {
					await model.rollback();
					return this.fail('更改成功');
				}
			} catch(e) {
				console.log(e);
				await model.rollback();
				return this.fail('编辑失败');
			}
		})
	}

	// 删除开卡单
	async deleteopencardeAction(){
		let orderid = this.post('id');

		/*
		 * 删除操作
		 * 首先要判断当前订单是否结账，是否存在
		 * 根据orderid把or_shop_order表里订单删除
		 * 然后把or_shop_orderinfo表里对于的信息也删除
		 */

		let oinfo = await this.model('or_shop_order').where({id: orderid}).find();

		if(think.isEmpty(oinfo)){
			return this.fail('当前订单不存在！');
		}
		if (oinfo.status) {
			return this.fail('当前订单已结账！');
		}

		//删除操作开始
		let model = this.model('or_shop_order');
		//方式一
		await model.transaction(async()=> {
			try{
				let delorder = await model.where({id: orderid}).delete();
				let delinfo = await this.model('or_shop_orderinfo').db(model.db()).where({orderid: orderid}).delete();
				if (delorder && delinfo) {
					await model.commit();
					return this.success('删除成功');
				} else {
					await model.rollback();
					return this.fail('删除失败');
				}
			}catch(e){
				console.log(e);
				await model.rollback();
				return this.fail("删除失败！");
			}
		})
	}

	// 订单信息显示和审核页面
	async cardinfoAction(){
		if (this.isGet) {
			let id = this.get('orderid');
			// 获取订单信息
			let oinfo = await this.model('or_shop_order').where({id:id}).find();
			// 获取订单的客户信息
			let ginfo = await this.model('or_guest').where({id:oinfo.guestid}).find();
			// 获取当前订单绩效分配的员工
			let uinfo = await this.model('or_shop_yejixianjin')
									.alias('yj')
									.field('yj.userid, yj.feat, u.name, u.username, u.zhichengid, p.name as zhicheng')
									.join('`think_or_app_user` u on u.id = yj.userid')
									.join('`think_or_position` p on p.id = u.zhichengid')
									.where({'yj.orderid':id})
									.select();
			// 获取订单分表数据
			let olist = await this.model('or_shop_orderinfo')
									.alias('i')
									.field('c.id,c.name,i.price,i.amount,i.discount,c.validity,c.typeid')
									.join('think_or_card c on i.typeid = c.id')
									.where({orderid:id}).select();
			// 获取收款金额及收款日志
			let alist = await this.model('or_shop_accountlog')
									.alias('l')
									.field('a.id,a.name,a.accounttype,a.accountsn,l.money as paymoney')
									.join('think_or_shop_account a on l.accountid = a.id')
									.where({orderid:id}).select();

			let data = {
				order 			: oinfo,
				guestinfo 	: ginfo,
				usersinfo 	: uinfo,
				orderinfo 	: olist,
				accountinfo : alist,
			}

			return this.json(data);
		} else {
			// 开卡订单审核
			let id = this.post('id');
			let whetherSH = await this.model('or_shop_order').where({id : id}).find();
			/*if (whetherSH.status == 2) {
				return this.fail('该订单已审核');
			}*/
			let res = await this.model('or_shop_order').where({id:id}).update({'status':2,'auditorid':this.shop_userinfo.id});
			return res?this.success({info:"审核成功！"}):this.fail('审核失败！');
		}
	}

	// 启用或禁用卡
	async unstopAction(){
		let id = this.get('id');
		let zt = this.get('zt');

		let res = await this.model('or_shop_card').where({id:id}).update({isdisabled:zt});

		if (zt == 0) {
			return res?this.success('启用成功'):this.fail('启用失败');
		} else {
			return res?this.success('禁用成功'):this.fail('禁用失败');
		}
	}

	// 获取店家信息
	async getshopinfoAction(){
		let sinfo = await this.model('or_department').where({id:this.shop_userinfo.departmentid}).find();
		return this.json(sinfo);
	}

	// 拉取编辑信息
	async geteditinfoAction(){
		let id = this.get('id');
		let order = await this.model('or_shop_order').where({id:id}).find();
		let ginfo = await this.model('or_guest').where({id:order.guestid}).field('id,name,phone').find();
		let cinfo = await this.model('or_shop_orderinfo')
								.alias('o')
								.join('`think_or_shop_guestcard` c on c.id = o.guestcardid')
								.where({'o.orderid':id})
								.select();
		let ainfo = await this.model('or_shop_accountlog')
								.alias('l')
								.field('l.accountid, l.money, a.name, a.accountsn, a.accounttype')
								.join('`think_or_shop_account` a on a.id = l.accountid')
								.where({'l.orderid':id})
								.select();
		let uinfo = await this.model('or_shop_yejixianjin')
								.alias('xj')
								.field('xj.feat, u.name, u.username, p.name as zhicheng')
								.join('`think_or_app_user` u on u.id = xj.userid')
								.join('`think_or_position` p on p.id = u.zhichengid')
								.where({'xj.orderid':id})
								.select();
		let data = {
			oinfo : order,
			ginfo : ginfo,
			cinfo : cinfo,
			ainfo : ainfo,
			uinfo : uinfo,
		}
		return this.json(data);
	}

	// 开卡反结账（必须为已结账未审核状态）
	async unpayAction(){
		let id = this.post('id');
		let shopid = this.shop_userinfo.departmentid;

		// 判斷是否可操作
		let order = await this.model('or_shop_order').where({id: id}).find()

		if (order.status != 1) {
			return this.fail('当前订单未结账或已审核')
		}

		let subjectlist = await this.model('or_shop_guestcardsubject').where({orderid: id}).select()
		let goodslist = await this.model('or_shop_guest_temp_reserve').where({orderid: id}).select()

		if (subjectlist.length > 0) {
			for (var i = subjectlist.length - 1; i >= 0; i--) {			
				if (subjectlist[i].num - subjectlist[i].nownum > 0) {
					return this.fail('该订单开出的卡项已经被使用，不能反结账！')
				}
			}
		}
		if (goodslist.length > 0) {
			for (var i = goodslist.length - 1; i >= 0; i--) {			
				if (goodslist[i].num - goodslist[i].nownum > 0) {
					return this.fail('该订单暂存的商品已被领走，不能反结账！')
				}
			}
		}
		
		let model = this.model('or_shop_order');
		await model.transaction(async ()=>{
			try {

				// 更改订单状态
				let resorder = await model.where({id: id}).update({
					auditorid: 0,
					status: 0
				})

				// 商品数量和库存日志
				let goodslog = await this.model('or_shop_goodslog').db(model.db()).where({ordertype: 'KKD', orderid: id}).select()
				let resgoods = 1, resgoodslog = 1,goodsdata = []
				if (goodslog.length > 0) {
					for (var i = goodslog.length - 1; i >= 0; i--) {
						let goods = await this.model('or_shop_goods').db(model.db()).where({goodsid: goodslog[i].goodsid, shopid: shopid}).find()
						goods.nums -= Number(goodslog[i].nums)
						goodsdata.push(goods)
					}
					resgoods = await this.model('or_shop_goods').db(model.db()).updateMany(goodsdata)
					resgoodslog = await this.model('or_shop_goodslog').db(model.db()).where({ordertype: 'KKD', orderid: id}).delete()
				}

				// 删除暂存商品
				let reszancun = await this.model('or_shop_guest_temp_reserve').db(model.db()).where({orderid: id, shopid: shopid}).delete()

				// 删除客户卡项表
				let resguestsubject = await this.model('or_shop_guestcardsubject').db(model.db()).where({orderid: id}).delete()

				// 如果有普通收款，删除日志，返还金额
				let resaccount = 1, resaccountlog = 1
				if (order.recemoney > 0) {
					let accountlog = await this.model('or_shop_accountlog').db(model.db()).where({ordertype: 'KKD', orderid: id}).select()
					let accountdata = []
					for (var i = accountlog.length - 1; i >= 0; i--) {
						let account = await this.model('or_shop_account').db(model.db()).where({id:accountlog[i].accountid}).find()
						account.balance -= Number(accountlog[i].money)
						accountdata.push(account)
					}
					resaccount = await this.model('or_shop_account').db(model.db()).updateMany(accountdata)
					resaccountlog = await this.model('or_shop_accountlog').db(model.db()).where({ordertype: 'KKD', orderid: id}).delete()
				}

				// 如果有余额或赠送余额支出
				let resdelbalancelog = 1, resbalance = 1
				// 判断是否使用余额
				if (order.usebalance != 0 || order.usegiftbalance != 0) {
					// 删除日志，返回金额
					resdelbalancelog = await this.model('or_shop_guest_accountlog').db(model.db()).where({ordertype: 'KKD',orderid:id}).delete()
					// 取金额
					let ginfo = await this.model('or_guest').db(model.db()).where({id: order.guestid}).find()
					resbalance = await this.model('or_guest').db(model.db()).where({id: order.guestid}).update({
						balance: ginfo.balance + Number(order.usebalance),
						giftbalance: ginfo.giftbalance + Number(order.usegiftbalance)
					})
				}

				// 删除业绩
				let resxianjin = await this.model('or_shop_yejixianjin').db(model.db()).where({orderid: id, feattype: 'KKD'}).delete();

				let resyejiticheng = await this.model('or_shop_yejiticheng').db(model.db()).where({orderid: id, ordertype: 'KKD'}).delete();

				if (resyejiticheng !== false && resxianjin !== false && resorder && resdelbalancelog && resbalance && resaccount && resaccountlog && resgoods && resgoodslog && resguestsubject !== false && reszancun !== false) {
					await model.commit();
					return this.success('反结账成功');
				} else {
					await model.rollback();
					return this.fail('反结账失败');
				}
				
			} catch (e) {
				console.log(e);
				await model.rollback();
				return this.fail('反结账失败');
			}
		})
	}

	// 重新分配订单业绩（已结账）现金业绩
	async resertallotAction(){
		let data = JSON.parse(this.post('data'))
		let nowtime = Math.round(Date.parse(new Date())/1000)
		// 获取订单实时信息判断状态
		let order = await this.model('or_shop_order').where({id: data.order.id}).find()

		// 如果状态为3则不能更改业绩
		if (2 == order.status) {
			return this.fail('该订单已经审核不能再分配业绩！')
		}
		if (0 == order.status) {
			return this.fail('该订单尚未结账，不能分配业绩！')
		}
		// 删除已经分配好的业绩重新分配
		let model = this.model('or_shop_yejixianjin');
		await model.transaction(async()=>{
			try{
				
				let resyeji = 1, resxianjin = 1, resreduce = 1, resdelxianjin = 1, resdelreduce = 1, resdelyeji = 1;

				resdelxianjin = await model.where({orderid: data.order.id, feattype: 'KKD'}).delete()
				resdelreduce = await this.model('or_shop_yejicardreduce').db(model.db()).where({orderid: data.order.id, feattype: 'KKD'}).delete()
				resdelyeji = await this.model('or_shop_yejiticheng').db(model.db()).where({orderid: data.order.id, ordertype: 'KKD'}).delete()


				if (data.yejilist.length > 0) {
					let yejidata = [], selluserList = [], reduceuserList = []
					data.yejilist.forEach((row) => {
						yejidata.push({
							shopid: this.shop_userinfo.departmentid,
							orderid: data.order.id,
							ordertype: 'KKD',
							xianjinyeji: row.xianjinyeji,
							kahaoyeji: row.kahaoyeji,
							userid: row.userid,
							bumenid: row.bumenid,
							xiaozuid: row.xiaozuid,
							guestid: data.order.guestid,
							fuwutype: row.fuwutype,
							addtime: data.order.addtime
						})
						if (row.xianjinyeji > 0) {
							selluserList.push({
								orderid 	: data.order.id,
								feattype	: 'KKD',
								shopid 		: this.shop_userinfo.departmentid,
								feat 		: row.xianjinyeji,
								userid 		: row.userid,
								bumenid 	: row.bumenid,
								xiaozuid 	: row.xiaozuid,
								guestid     : data.order.guestid,
								addtime 	: data.order.addtime
							})
						}
						if (row.kahaoyeji > 0) {
							reduceuserList.push({
								orderid 	: data.order.id,
								feattype	: 'KKD',
								shopid 		: this.shop_userinfo.departmentid,
								feat 		: row.kahaoyeji,
								userid 		: row.userid,
								bumenid 	: row.bumenid,
								xiaozuid 	: row.xiaozuid,
								guestid     : data.order.guestid,
								addtime 	: data.order.addtime
							})
						}
					})

					if (selluserList.length > 0) {
						resxianjin = await this.model('or_shop_yejixianjin').db(model.db()).addMany(selluserList);
					}
					if (reduceuserList.length > 0) {
						resreduce = await this.model('or_shop_yejicardreduce').db(model.db()).addMany(reduceuserList);
					}
					resyeji = await this.model('or_shop_yejiticheng').db(model.db()).addMany(yejidata)
				}

				if (resyeji && resxianjin && resreduce && resdelxianjin !== false && resdelreduce !== false && resdelyeji) {
					await model.commit();
					return this.success({data:200, info:'编辑成功'});
				} else {
					await model.rollback();
					return this.fail("编辑失败！");
				}
			}catch(e){
				console.log(e)
				await model.rollback();
				return this.fail("编辑失败！");
			}
		})
	}

	// 获取分店未停用项目接口
	async getshopsubjectAction(){

		let shopid = this.shop_userinfo.departmentid;

		let list = await this.model('or_shop_subject')
				.alias('ss')
				.field('ss.subjectid, s.id, s.name, ss.price, s.number')
				.join('`think_or_subject` s on s.id=ss.subjectid')
				.where({'ss.shopid': shopid, 'ss.isdisable': 0})
				.select();

		return this.json(list);
	}

	// shop created customs of cards
	async createcardAction(){

		let data = JSON.parse(this.post('data'));
		let category = this.post('type');

		let shopid = this.shop_userinfo.departmentid;
		let time = Math.round(new Date().valueOf()/1000);

		// check number or name is repeat.
		let isrepeat = await this.model('or_shop_card').where('shopid='+shopid+' AND (number="'+data.number+'" OR name="'+data.name+'")').select();

		if (!think.isEmpty(isrepeat)) {
			return this.fail('卡项编号或名称重复');
		}

		let model = this.model('or_shop_card');
		await model.transaction(async ()=>{

			try {

				let cardleng = await model.where({shopid: shopid}).count('id');

				let addone = {
						no: cardleng+1,
						name: data.name,
						number: data.number,
						price: data.price,
						category: category,
						remarks: data.remarks,
						addtime: time,
						shopid: shopid,
						tdtype: data.tdtype,
					}

					if (data.tdtype==1) addone.percent = Number(data.percent/100).toFixed(4);
					else addone.fixed = data.fixed;

				let cardid = 0, tjkx = 0;

				if (category == 1) {

					addone.validity = data.validity;

					cardid = await model.add(addone);

					let addtwo = [];

					data.slist.forEach((v)=>{
						addtwo.push({
							cardid: cardid,
							subjectid: v.subjectid,
							// subjectnumber: v.number,
							price: v.price,
							amount: v.amount,
							xhprice: v.xhprice*1,
						})
					})

					tjkx = await this.model('or_shop_cardsubject').db(model.db()).addMany(addtwo);

				} else {

					cardid = await model.add(addone);

					let addthree = [];

					data.slist.forEach((v)=>{
						addthree.push({
							cardid: cardid,
							subjectid: v.subjectid,
							// subjectnumber: v.number,
							price: v.price,
							disprice: v.disprice,
							num: v.num
						})
					})

					tjkx = await this.model('or_shop_cardsubject').db(model.db()).addMany(addthree);

				}
				if (cardid && tjkx) {
					await model.commit();
					return this.success('创建成功');
				} else {
					await model.rollback();
					return this.fail('创建失败');
				}
			} catch(e) {
				console.log(e)
				await model.rollback();
				return this.fail('创建失败');
			}

		})
	}

	// look shop card infomation
	async lookcardinfoAction(){

		let id = this.get('id');

		let info = await this.model('or_shop_card').where({id: id}).find();

		let list = await this.model('or_shop_cardsubject')
		.alias('cs')
		.field('cs.*, s.name, s.number')
		.join('`think_or_subject` s on s.id=cs.subjectid')
		.where({'cs.cardid': id})
		.select();

		let data = {
			info: info,
			list: list
		}

		return this.json(data);
	}

	// edit shop card infomation
	async editcardAction(){
		let data = JSON.parse(this.post('data'));
		let dels = JSON.parse(this.post('dels'));
		let category = this.post('type');

		let shopid = this.shop_userinfo.departmentid;

		let isrepeat = await this.model('or_shop_card').where('shopid="'+shopid+'" AND (number="'+data.number+'" OR name="'+data.name+'") AND id!='+data.id).find();

		if (!think.isEmpty(isrepeat)) {
			return this.fail('更改的卡名称或编号重复');
		}

		let model = this.model('or_shop_card');

		await model.transaction(async ()=>{

			try {

				if (dels.length) {
					let del_res = await this.model('or_shop_cardsubject').db(model.db()).where({id: ['IN',dels]}).delete();
					if (!del_res) {
						await model.rollback();
						return this.fail('删除项目失败');
					}
				}

				let updatecard = {
					name: data.name,
					number: data.number,
					price: data.price,
					remarks: data.remarks,
					validity: data.validity,
					tdtype: data.tdtype
				}

				if (data.tdtype==1) {
					updatecard.percent = Number(data.percent/100).toFixed(4);
					updatecard.fixed = 0;
				} else {
					updatecard.percent = 0;
					updatecard.fixed = data.fixed;
				}

				let upcard_res = await model.where({id: data.id}).update(updatecard);
				let add_kx = [];
				for (var i = data.slist.length - 1; i >= 0; i--) {
					if (data.slist[i].id) {

						let gg_res = await this.model('or_shop_cardsubject').db(model.db()).where({id: data.slist[i].id}).update({
							'price': data.slist[i].price,
							'disprice': data.slist[i].disprice,
							'num': data.slist[i].num,
							'amount': data.slist[i].amount,
							'xhprice': data.slist[i].xhprice*1
						});

						if (!gg_res) {
							await model.rollback();
							return this.fail('更新卡项失败');
						}

					} else {
						add_kx.push({
							cardid: data.id,
							subjectid: data.slist[i].subjectid,
							subjectnumber: data.slist[i].number,
							price: data.slist[i].price,
							disprice: data.slist[i].disprice,
							num: data.slist[i].num,
							amount: data.slist[i].amount,
							xhprice: data.slist[i].xhprice*1
						})
					}
				}
				
				if (add_kx.length) {
					let addkx_res = await this.model('or_shop_cardsubject').db(model.db()).addMany(add_kx);
					if (!addkx_res) {
						await model.rollback();
						return this.fail('添加卡项失败');
					}
				}
				
				await model.commit();
				return this.success('更改卡项成功');

			} catch(e) {
				console.log(e);
				await model.rollback();
				return this.fail('更改失败');
			}
		})
	}
	// 获取分配的业绩
	async getorderfenpeilistAction () {
		let id = this.get('id')
		let yejilist = await this.model('or_shop_yejiticheng')
		.alias('y')
		.field('y.*,u.name')
		.join('left join `think_or_app_user` u on y.userid = u.id')
		.where({'y.ordertype': 'KKD', 'y.orderid': id})
		.select()
		return this.json(yejilist)
	}

	// 计算订单的现金提成，卡耗提成，手工提成
	async getjisuantichengAction () {
		let id = this.post('id')
		// 列出订单信息
		let  orderlist = await this.model('or_shop_orderinfo').where({orderid: id}).select()
		let ax = 0, ak = 0 // 总现金业绩，总卡耗业绩
		let xt = 0, kt = 0, st = 0 // 总现金卡耗手工提成
		// 获取开卡的提点
		let baseConfig = await this.model('or_shop_basis').where({shopid: this.shop_userinfo.departmentid}).find()
		let openCardTidian = baseConfig.kaikapercent
		for (var i = orderlist.length - 1; i >= 0; i--) {
			let x = 0, k = 0
			if (orderlist[i].consumetype == 1) {
				// 普通的产品消费
				x = orderlist[i].usemoney
				k = orderlist[i].usebalance + Number(orderlist[i].usegiftbalance)
				/*if (orderlist[i].type == 1) {
					// 取商品
					let goods = await this.model('or_shop_goods')
					.where({goodsid: orderlist[i].typeid, shopid: this.shop_userinfo.departmentid})
					.find()
					// 取现金业绩和卡耗业绩
					orderlist[i].xianjinticheng = goods.tdtype == 1 ? x * goods.percent : x / (x + k) * orderlist[i].num * goods.fixed
					orderlist[i].kahaoticheng = goods.khtdtype == 1 ? k * goods.khpercent : k / (x + k) * orderlist[i].num * goods.khfixed			
				}
				if (orderlist[i].type == 2) {
					let subject = await this.model('or_shop_subject').where({subjectid: orderlist[i].typeid, shopid: this.shop_userinfo.departmentid}).find()
					orderlist[i].xianjinticheng = subject.xstdtype == 1 ? x * subject.xspercent : x / (x + k) * orderlist[i].num * subject.xsfixed
					orderlist[i].kahaoticheng = 0
					orderlist[i].shougongticheng = 0
				}

				if (orderlist[i].type == 3) {
					let card = await this.model('or_shop_card').where({id: orderlist[i].typeid}).find()
					orderlist[i].xianjinticheng = card.tdtype == 1 ? x * card.percent : x / (x + k) * orderlist[i].num * card.fixed
				}*/
				console.log(orderlist[i])
				orderlist[i].xianjinticheng = x * openCardTidian
				if (orderlist[i].cardtype == 1 && k > 0) {
					orderlist[i].kahaoticheng = k * openCardTidian
				}
			}
			
			orderlist[i].xianjinticheng = orderlist[i].xianjinticheng ? orderlist[i].xianjinticheng.toFixed(2) : 0
			orderlist[i].kahaoticheng = orderlist[i].kahaoticheng ? orderlist[i].kahaoticheng.toFixed(2) : 0 
			orderlist[i].shougongticheng = 0
			ax += Number(x)
			ak += Number(k)
			
			xt += Number(orderlist[i].xianjinticheng)
			kt += Number(orderlist[i].kahaoticheng)
			st += Number(orderlist[i].shougongticheng)
		}
		let fenpeilist = await this.model('or_shop_yejiticheng')
		.alias('y')
		.field('y.*, u.name')
		.join('left join `think_or_app_user` u on y.userid = u.id')
		.where({'y.ordertype': 'KKD', 'y.orderid': id})
		.select()
		let order = await this.model('or_shop_order').where({id: id}).find()
		if (fenpeilist.length > 0 && order.status != 2) {
			for (var i = fenpeilist.length - 1; i >= 0; i--) {
				let xianjin =  (fenpeilist[i].xianjinyeji / ax) * xt ? ((fenpeilist[i].xianjinyeji / ax) * xt).toFixed(2) : 0
				let kahao = (fenpeilist[i].kahaoyeji / ak) * kt ? ((fenpeilist[i].kahaoyeji / ak) * kt).toFixed(2) : 0
				fenpeilist[i].xianjinticheng =  xianjin
				fenpeilist[i].kahaoticheng =  kahao
			}
		}
		let data = {
			orderlist: orderlist,
			fenpeilist: fenpeilist
		}
		return this.json(data)
	}

}